package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 该类解析SqlMappConfig.xml
 */
public class XMLConfigBuild {

    public XMLConfigBuild() {
        this.configuration = new Configuration();
    }

    private Configuration configuration;

    /***
     *该方法使用dom4j对配置文件进行解析，封装到configuration中
     */
    public Configuration parseConfig(InputStream in) throws DocumentException, PropertyVetoException, ClassNotFoundException {

        Document document = new SAXReader().read(in);

        //拿到了根对象
        Element rootElement = document.getRootElement();
        //获取所有property标签的值
        List<Element> list = rootElement.selectNodes("//property");

        //保存所有属性值
        Properties properties = new Properties();
        for(Element element:list){
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }

        //设置c3p0连接池
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        //填充configuration
        configuration.setDataSource(comboPooledDataSource);

        //mapper.xml解析  拿到路径---加载成字节输入流---dom4j解析
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        XMLMapperBuilder xmlMapperBuilder = new
                XMLMapperBuilder(configuration);
        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");
            InputStream resourceAsSteam =
                    Resources.getResourceAsStream(mapperPath);
            xmlMapperBuilder.parse(resourceAsSteam);
        }
        return configuration;
    }
}
